package crp.core.resource.domain.models;

import com.qwlabs.lang.F2;
import crp.core.shared.LifecycleStatus;
import crp.core.shared.PublicStatus;
import crp.core.shared.PublishStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

import static crp.core.shared.LifecycleStatus.ENABLED;
import static crp.core.shared.PublicStatus.PUBLIC;
import static crp.core.shared.PublishStatus.PUBLISHED;

@Getter
@Builder
@AllArgsConstructor
public class ResourceQuery {
    private final String courseId;
    private final LifecycleStatus status;
    private final PublishStatus publishStatus;
    private final PublicStatus publicStatus;
    private final ResourceQueryScene scene;
    private final AttachmentType attachmentType;

    public String buildNativeSql() {
        StringBuffer sql = new StringBuffer("select * from resource r where 1 = 1 ");
        F2.ifPresent(courseId, () -> {
            sql.append(String.format(" join course_resource cr on cr.course_id = %s and cr.resource_id = r.id ", courseId));
        });
        if (scene == ResourceQueryScene.STUDENT) {
            // 学生只能查已启用的且(发布或公开的)资源
            sql.append(String.format(" and r.status = '%s' and ( r.public_status = '%s' or r.publish_status = '%s' ) ",
                    ENABLED, PUBLIC, PUBLISHED));
        } else {
            F2.ifPresent(status, () -> {
                sql.append(String.format(" and r.status = '%s' ", status));
            });
            F2.ifPresent(publicStatus, () -> {
                sql.append(String.format(" and r.public_status = '%s' ", publicStatus));
            });
            F2.ifPresent(publishStatus, () -> {
                sql.append(String.format(" and r.publish_status = '%s' ", publishStatus));
            });
        }
        F2.ifPresent(attachmentType, () -> {
            sql.append(String.format(" and r.attachment ->> 'type' = '%s' ", attachmentType));
        });
        return sql.toString();
    }
}
